/**
 * @desc: 找家纺ERP项目主要内容入口文件,包含权限管理
 * @author: Elvis
 */

import React, { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import CommonLoading from "@/components/CommonLoading";
import ViewsLayout from "./ViewsLayout";
import ErrorBoundary from "./ErrorBoundary";
import useUserStore from "@/stores/user";
import { getToken, setToken } from "@/utils/authority";
import { getSearchParamsObj } from "@/utils/utils.jsx";
import { getFieldConfig } from '@/services/common';

const BasicLayout = () => {
	const menuData = useUserStore(state => state.menuData);

	const initData = useUserStore(state => state.initData);

	const navigate = useNavigate();

	const [loading, setLoading] = useState(false);

	const [initTab, setInitTab] = useState([{ key: "/home", tab: "首页", lock: true }]);

	const location = useLocation();

	useEffect(() => {
		initPage();
		getTabList();
	}, []);

	//获取菜单数据
	const getTabList = async () => {
		setLoading(true);
		const { success, data } = await getFieldConfig({ code: 'globalHeaderMenu' });
		setLoading(false);
		if (success) {
			if (data?.param) {
				const arr = JSON.parse(data.param);
				setInitTab(arr);
			}
		}
	}

	const initPage = async () => {
		const urlParams = getSearchParamsObj(location.search);
		//校验商城跳转过来的url
		if (urlParams.token) {
			console.log("商城跳转url", urlParams);
			await setToken(`bearer ${urlParams.token}`);
			if (urlParams.app_type) {
				await sessionStorage.setItem("mall_authorize_pdd", urlParams.app_type);
			} else if (urlParams.key == 4) {
				await sessionStorage.setItem("jump_tab_key", urlParams.key);
			}
			if (location.pathname) {
				navigate(location.pathname, { replace: true });
			} else {
				navigate("/home", { replace: true });
			}
		}

		//校验是否登录
		if (!getToken()) {
			navigate("/user/login");
		}

		//获取菜单和
		initData();
	};

	if (menuData.length == 0 || loading) {
		return <CommonLoading loading={true} />;
	}

	return (
		<ErrorBoundary>
			<ViewsLayout initTab={initTab} menuData={menuData} />
		</ErrorBoundary>
	);
};

export default BasicLayout;
